package chatManagers;

/*
 * EventManager.java
 *
 * Created on September 10, 2006, 6:42 PM
 *
 * Handles requests from setInterval() listeners in the common.js file
 *
 */

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class EventManager extends HttpServlet {
    
    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/plain");
        response.setHeader("Cache-control", "no-cache");
        PrintWriter out = response.getWriter();
        
        String responseString = new String();
        int chatID = 0;
        int userID = 0;
        int lastMsgID = 0;
        String method = request.getParameter("doAction");
        ResultSet rs = null;
        
        DBMSManager dbm = new DBMSManager();
        
        if(method.equals("addComment")) {
            chatID = Integer.parseInt(request.getParameter("chatid"));
            userID = Integer.parseInt(request.getParameter("userid"));
            lastMsgID = new Integer(request.getParameter("lastmsgid")).intValue();
            String comment = request.getParameter("comment");
            
            // Be sure this is an active chat
            if (chatID > 0) {
                dbm.AddPost(chatID, userID, comment);
            }
            
            try {
                rs = dbm.getLatestPosts(chatID, lastMsgID);
                responseString += this.printPosts(rs);
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace(out);
            } finally {
                dbm.closeConnection();
            }
                        
            // Return an HTML formatted list of all active chat members
        } else if (method.equals("getAllChatters")) {
            try {
                chatID = Integer.parseInt(request.getParameter("chatid"));
                rs = dbm.getMembers(chatID);
                responseString += printAllChatters(rs);
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace(out);
            } finally {
                dbm.closeConnection();
            }
            
            // Return the private messages for the given user in the given chat
        } else if (method.equals("getPrivateMessages")) {
            chatID = Integer.parseInt(request.getParameter("chatid"));
            userID = Integer.parseInt(request.getParameter("userid"));
            try {
                rs = dbm.getPrivateMessages(chatID, userID);
                responseString += printPvtMessages(rs, userID);
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace(out);
            } finally {
                dbm.closeConnection();
            }
            
            // Load the contents of the chat
        } else if (method.equals("loadChat")) {
            chatID = Integer.parseInt(request.getParameter("chatid"));
            userID = dbm.checkLogin(request.getRemoteUser());
            boolean isActive = dbm.isChatActive(chatID);
            
            // If the user has been booted out of the chat room, update the db;
            // otherwise, check if the chat is still active, then print out the posts.
            if(userID==0) {
                dbm.unsetUserChat(userID);
                responseString += "false";
            } else {
                try {
                    // If the chat is active, get the latest 15 posts; otherwise, close the chat
                    if(isActive) {
                        rs = dbm.getAllPosts(chatID, -1, 15);
                        responseString += this.printPosts(rs);
                    } else {
                        responseString += isActive;
                        dbm.EndChat(chatID);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    dbm.closeConnection();
                }
            }
            
            // Get any new messages
        } else if (method.equals("getNewMessages")) {
            chatID = Integer.parseInt(request.getParameter("chatid"));
            userID = dbm.checkLogin(request.getRemoteUser());
            lastMsgID = new Integer(request.getParameter("lastmsgid")).intValue();
            boolean isActive = dbm.isChatActive(chatID);
            
            // If the user has been booted out of the chat room, update the db;
            // otherwise, check if the chat is still active, then print out the posts.
            if(userID==0) {
                dbm.unsetUserChat(userID);
                responseString += "false";
            } else {
                try {
                    // If the chat is active, get the latest 15 posts; otherwise, close the chat
                    if(isActive) {
                        rs = dbm.getLatestPosts(chatID, lastMsgID);
                        responseString += this.printPosts(rs);
                    } else {
                        responseString += isActive;
                        dbm.EndChat(chatID);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    dbm.closeConnection();
                }
            }
        }
        
        //System.out.print(responseString);
        out.print(responseString);
        out.close();
    }
    
    public String printAllChats(ResultSet r) {
        String s = "";
        try {
            if (r==null) {
                s +="<p>No Active Chats</p>";
            } else {
                s +="<p>Active Chats</p><ul>";
                while(r.next()) {
                    s += "<li id=\"" + r.getString("ID") +
                            "\" onmouseup=\"signon(this)\" >"+
                            "<h3>"+r.getString("name")+" (Leader:"
                            + r.getString("owner")+")</h3></li>";
                }
                s +="</ul>";
            }
        } catch (SQLException se) {
            se.printStackTrace();
        }
        return s;
    }
    
    public String printAllChatters(ResultSet r) {
        String s = "";
        try {
            if (r==null) {
                s +="<p>Sorry, nobody's here</p>";
            } else {
                while (r.next()) {
                    String uid = r.getString("ID");
                    String user = r.getString("username");
                    //user = user.substring(0, (user.length() - 2));
                    s += "<p id=\"" + uid + "\">"
                            //+ "onmouseOver=\"setCursor()\" onmouseout=\"resetCursor()\" "
                            //+ "onmouseup='showPvtMsg(" + uid + ", \"" + user + "\")'>"
                            + "<img align=\"absmiddle\" border=\"0\" hspace=\"5\" src=\"../img/chat_user.gif\" />"
                            //+ "<span class=\"private\" title=\"Send " + user + " a private message\">"
                            + user
                            //+ "</span>"
                            + "</p>";
                }
            }
        } catch (SQLException se) {
            se.printStackTrace();
        }
        return s;
    }
    
    public String printPosts(ResultSet r) {
        String s = "";
        try {
            if (r==null) {
                s = "<p>NO POSTS TO CHAT</p>";
            } else {
                while(r.next()) {
                    java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("h:mm aa");
                    String user = r.getString("uName");
                    java.sql.Time d = r.getTime("mtime");
                    String message = r.getString("message");
                    String mID = r.getString("mid");
                    
                    String dt = df.format(d);
                    s += "<p id=\"" + mID + "\">"
                            + "<b>" + user +"</b>: "
                            + "<span class=\"datetime\">(" + dt + ")</span> "
                            + message + "</p>";
                }
            }
        } catch (SQLException se) {
            se.printStackTrace();
        }
        return s;
    }
    
    public String printPvtMessages(ResultSet r, int u) {
        String s = "";
        try {
            if (r!=null) {
                while (r.next()) {
                    //java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("hh:mm aa");
                    String user = r.getString("uName");
                    user = user.substring(0, (user.length() - 2));
                    //java.sql.Time d = r.getTime("mtime");
                    String message = r.getString("message");
                    String mID = r.getString("mid");
                    
                    s += "<p id=\"" + mID + "\" " +
                            "onmouseOver='setCursor()' onmouseout='resetCursor()'" +
                            "onmouseup='showPvtMsg(" + u + ", \"" + user + "\")'>" +
                            "<img align=\"absmiddle\" border=\"0\" hspace=\"5\" src=\"../img/chat_private.gif\" />"
                            + "<span class=\"private\" title=\"Send " + user + " a private message\">"
                            + user + "</span>: " + message + "</p>";
                    System.out.println(s);
                }
            }
        } catch (SQLException se) {
            se.printStackTrace();
        }
        return s;
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}
